<template>
    <div id="addGoods">
        <!-- title -->
        <div class="title">
            <bread-crumb>{{ title }}</bread-crumb>
           
            <div class="btn">
                <!-- <el-button size="mini" type="success" @click="addBanner">添加商品</el-button> -->
            </div>
        </div>

        <!-- table -->
        <div class="table">
            <el-form :model="goodsInfo" label-width="100px">
                <el-form-item label="商品ID" v-if="goodsInfo.id || goodsInfo._id">
                    <el-input v-model="goodsInfo.id" disabled ></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <div class="classbox">
                        <div class="addClass">
                            <el-tag
                            :key="tag"
                            v-for="tag in goodsInfo.beLong"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)">
                            {{tag}}
                            </el-tag>
                        </div>
                        <div class="allClass">
                            <el-select v-model="goodsClass" @change="SelectChange" placeholder="请选择商品分类" v-if="isReady">
                                <el-option-group
                                v-for="group in classList"
                                :key="group.classname"
                                :label="group.classname">
                                <el-option
                                    v-for="item in group.children"
                                    :key="item._id"
                                    :label="item.classname"
                                    :value="item.classname">
                                </el-option>
                                </el-option-group>
                            </el-select>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品标题">
                    <el-input v-model="goodsInfo.title" maxlength="30"></el-input>
                </el-form-item>

                <el-form-item label="商品库存">
                    <el-input type="number" v-model="goodsInfo.stock" maxlength="30"></el-input>
                </el-form-item>

                <el-form-item label="商品规格">
                    <div class="guides">
                        <div class="guidebox" v-for=" (item, index) in goodsInfo.guide" :key="index" >
                            <div class="guide_name">
                                <span class="name">规格名称</span>
                                <el-input v-model="item.name" ></el-input>
                            </div>
                            <div class="guide_stock">
                                <span class="name">库存</span>
                                <el-input type="number"  v-model="item.stock" ></el-input>
                            </div>
                            <div class="guide_price">
                                <span class="name">价格</span>
                                <el-input type="number" v-model="item.price" ></el-input>
                            </div>
                            <div class="close" @click="DeleteGuide(index)">
                                <i class="el-icon-circle-close"></i>
                            </div>
                        </div>
                    </div>
                    <div class="addguidebtn">
                        <el-button type="primary" icon="el-icon-plus" @click="addGuide" >添加规格</el-button>
                    </div>
                </el-form-item>

                <!-- 商品主图 -->
                <el-form-item label="商品主图">
                    <div class="mainimglist" >
                        <img v-for="item in goodsInfo.mainImage" :key="item" :src="item" @click="deleteImg(item)" alt="">
                    </div>
                    <el-tabs type="border-card">
                        <el-tab-pane >
                            <span slot="label"><i class="el-icon-camera"></i>相册选择</span>
                            <div class="allimglist" v-if="goodsInfo.mainImage && goodsInfo.mainImage.length" >
                                <img :src="item" v-for="item in goodsInfo.mainImage" :key="item" alt="">
                            </div>
                            <!-- imglist 相册图片列表 -->
                            <div class="allimglist" v-if="AllImage.length" >
                                <img :src="item" v-for="item in AllImage" :key="item" @click="getImage(item)" alt="">
                            </div>
                            <!-- 分页 -->
                            <div class="page">
                                <el-pagination
                                small
                                layout="prev, pager, next"
                                :current-page="CurrentPage"
                                :page-size="PageSize"
                                @current-change="onPageChange"
                                :total="total">
                                </el-pagination>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane >
                            <span slot="label"><i class="el-icon-upload"></i>本地上传</span>

                            <!-- <div class="allimglist" v-if="goodsInfo.mainImage.length" >
                                <img :src="item" v-for="item in goodsInfo.mainImage" :key="item" alt="">
                            </div> -->

                            <div class="upload" v-if="MainisReady">
                                <el-upload
                                action="https://jsonplaceholder.typicode.com/posts/"
                                list-type="picture-card"
                                :auto-upload="false"
                                :limit="mainLimit"
                                multiple
                                ref="upload"
                                :on-change="onUpLoadChange"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove">
                                <i class="el-icon-plus"></i>
                                </el-upload>
                                <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                                </el-dialog>

                                <div class="uploadbtn" style="text-align:center">
                                    
                                        <el-popover
                                            placement="top-start"
                                            title="提示"
                                            width="200"
                                            trigger="hover"
                                            content="商品主图最多上传5张">
                                            <el-button slot="reference" size="mini" type="primary" @click="SubMain">立即上传</el-button>
                                        </el-popover>
                                    
                                </div>
                            </div>
                        </el-tab-pane>
                        
                    </el-tabs>
                </el-form-item>

                <el-form-item label="商品价格">
                    <el-input type="number" v-model="goodsInfo.price" @blur="checkPrice" ></el-input>
                </el-form-item>

                <el-form-item label="商品折扣">
                    <el-input type="number" v-model="goodsInfo.sale" @blur="checkSale" ></el-input>
                </el-form-item>

                <el-form-item label="一级分佣比列">
                    <el-input type="number" v-model="goodsInfo.proportion" @blur="checkPro" ></el-input>
                </el-form-item>

                <el-form-item label="二级分佣比列">
                    <el-input type="number" v-model="goodsInfo.secproportion" @blur="checkPor" ></el-input>
                </el-form-item>

                <el-form-item label="是否上架">
                    <el-select v-model="goodsInfo.status">
                        <el-option v-for="item in StatusOption" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 商品详情页-->
                <el-form-item label="商品详情页">
                    
                   <vue-ueditor-wrap v-model="goodsInfo.ImageList" :config="myConfig" ></vue-ueditor-wrap>
                </el-form-item>

                <el-form-item>
                    <div class="btnbox">
                        <el-button @click="Cancel">取消</el-button>
                        <el-button type="primary" @click="addGoodsInfo">确定</el-button>
                    </div>
                </el-form-item>

            </el-form>
        </div>


        

    </div>
</template>

<script>
    import BreadCrumb from "@/components/index/BreadCrumb"
   import VueUeditorWrap from 'vue-ueditor-wrap'
    export default {
        components: {
            BreadCrumb,
            VueUeditorWrap
        },
        data() {
            return {
               title: "",
               goodsInfo: {},
               goodsClass: "",
               beLong: [],
               classList: [],
               isReady: true,
               MainisReady: true,
               imageLists: true,
               
               imgListLimit: 15,
               AllImage: [],
               CurrentPage: 1,
               PageSize: 10,
               total: 0,
               dialogImageUrl: '',
               dialogVisible: false,
               dialogImageUrl1: '',
               dialogVisible1: false,
               mainLimit: 0,
               ListLimit: 0,
               ListisReady: true,
               main: [],
               list: [],
               StatusOption: [
                   { value: 1, label: "立即上架" },
                   { value: 2, label: "放入仓库" },
               ],
               myConfig: {
                    // 编辑器不自动被内容撑高
                    autoHeightEnabled: false,
                    // 初始容器高度
                    initialFrameHeight: 240,
                    // 初始容器宽度
                    initialFrameWidth: '100%',
                    // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
                    serverUrl: 'https://www.adkang.cn/UEditor/php/controller.php',
                    // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
                    UEDITOR_HOME_URL: '/UEditor/'
                }
            }
        },
        created () {
            let type = this.$route.params.type;
            if (type == "add") {
                this.title = "添加商品"
                this.goodsInfo = {
                    title: "",
                    price: "",
                    sale: "",
                    proportion: "",
                    secproportion: "",
                    mainImage: [],
                    ImageList: "",
                    status: 1,
                    stock: "",
                    guide: [],
                    beLong: []
                }
                this.mainLimit = 5
            } else {
                this.title = "编辑商品"
                this.getGoodsByID( type )
            }
        },
        computed: {
           
        },
        watch: {
            
        },
        mounted () {
            
            this.getClassList()
            this.getAllImage()
        },
        methods: {
           // 根据ID 查找商品
            async getGoodsByID( id ) {
                this.goodsInfo = {}
                let res = await this.$axios.post("/admin/findGoodsByID", { id })
                let code = res.data.code 
                if (code == 200) {
                    this.goodsInfo = res.data.data
                    this.goodsInfo.id = this.goodsInfo._id
                } 
                
                this.mainLimit = 5 - this.goodsInfo.mainImage.length
                if (this.mainLimit == 0) {
                    this.MainisReady = false
                }
                
            },

            // 获取所有分类
 
            async getClassList() {
                
                this.classList = []
                
                let res = await this.$axios.post("/admin/ShowClass")
               
                let code = res.data.code 
                if (code == 200) {
                    this.classList = res.data.data.clas
                }
            },


            // 选择类目变化时
            SelectChange(e) {
                let hasData = this.goodsInfo.beLong.indexOf(e)
                if (hasData == -1) {
                    this.goodsInfo.beLong.push(e)
                    let length = this.goodsInfo.beLong.length
                    if (length >= 5 ) {
                        this.isReady = false 
                    }
                    this.goodsClass = ""
                } else {
                    this.$message.error("该分类已存在")
                    this.goodsClass = ""
                }
            },

            // 点击删除已选分类
            handleClose(tag) {
                this.goodsInfo.beLong.splice(this.goodsInfo.beLong.indexOf(tag), 1);
            },

            // 获取相册中所有图片
            async getAllImage( pages ) {
                let page = pages ? pages : 1
                console.log(page);
                
                let res = await this.$axios.post("/admin/allImage", { page })
                console.log(res);
                
                let code = res.data.code
                if (code == 200) {
                    this.AllImage = res.data.data.res
                    this.total = res.data.data.count
                }
            },

            // 页码变化
            onPageChange(e) {
                this.getAllImage(e)
            },
            // 移除图片
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            // 放大图片
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },

            // 移除图片
            handleRemoved(file, fileList) {
                console.log(file, fileList);
            },
            // 放大图片
            handlePictureCardPreviewd(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },

            // 上传图片发生变化
            onUpLoadChange(file, files) {
                this.main = []
                let arr = []
                let length = files.length
                setTimeout(() => {
                    files.forEach(el => {
                        arr.push(el.raw)
                    })
                    this.main = arr.slice(0, length)
                }, 1000)
                
            },

            // 上传详情页发生变化
            onUpLoadChanged(file, files) {
                this.list = []
                let arr = []
                let length = files.length
                setTimeout(() => {
                    files.forEach(el => {
                        arr.push(el.raw)
                    })
                    this.list = arr.slice(0, length)
                }, 1000)
                
            },

            // 上传商品主图

            async SubMain() {
                let list = []
                if (this.main.length) {
                    let fd = new FormData()
                    this.main.forEach( el => {
                        fd.append("main", el)
                    })

                    let res = await this.$axios.post("/admin/addGoodsMain", fd)
                    // console.log(res);
                    
                    let code = res.data.code
                    if (code == 202) {
                        list = res.data.data
                        this.goodsInfo.mainImage = this.goodsInfo.mainImage.concat(list)
                        this.mainLimit = 5 - this.goodsInfo.mainImage.length
                        let length = this.goodsInfo.mainImage.length 
                        if( length >= 5) {
                            this.MainisReady = false
                        } else {
                            this.MainisReady = true
                        }
                        
                        this.$refs.upload.clearFiles()
                    } 
                } else {
                    return false
                }
            },

            // 上传详情页

            // async SubList() {
            //     let list = []
            //     if (this.ImageList.length) {
            //         let fd = new FormData()
            //         this.list.forEach( el => {
            //             fd.append("imglist", el)
            //         })

            //         let res = await this.$axios.post("/admin/addGoodsImgList", fd)
            //         // console.log(res);
                    
            //         let code = res.data.code
            //         if (code == 202) {
            //             list = res.data.data
            //             this.goodsInfo.ImageList = this.goodsInfo.ImageList.concat(list)
            //             this.ListLimit = 15 - this.goodsInfo.mainImage.length
            //             let length = this.goodsInfo.ImageList.length 
            //             if( length >= 15) {
            //                 this.ListisReady = false
            //             } else {
            //                 this.ListisReady = true
            //             }
                        
            //             this.$refs.upload.clearFiles()
            //         } 
            //     } else {
            //         return false
            //     }
            // },

            // 检测sale是否大于 100
            checkPrice() {
                let price = this.goodsInfo.price
                let isok = price.indexOf(0) == 0
                
                if (isok) {
                    this.$message.error("输入不规范,请重新输入")
                    this.goodsInfo.price = ""
                } else {
                    if (price < 0 ) {
                        this.$message.error("商品价格不能小于0%")
                        this.goodsInfo.price = ""
                    }
                }
            },
            checkSale() {
                let price = this.goodsInfo.sale
                let isok = price.indexOf(0) == 0
          
                if (isok) {
                    this.$message.error("输入不规范,请重新输入")
                    this.goodsInfo.sale = ""
                } else {
                    if (price < 0 || price > 100) {
                        this.$message.error("商品折扣不能大于100%或小于0%")
                        this.goodsInfo.sale = ""
                    }
                }
            },
            checkPro() {
                let price = this.goodsInfo.proportion
                let isok = price.indexOf(0) == 0
          
                if (isok) {
                    this.$message.error("输入不规范,请重新输入")
                    this.goodsInfo.proportion = ""
                } else {
                    if (price < 0 || price > 100) {
                        this.$message.error("商品佣金不能大于100%或小于0%")
                        this.goodsInfo.proportion = ""
                    }
                }
            },
            checkPor() {
                let price = this.goodsInfo.secproportion
                let isok = price.indexOf(0) == 0
          
                if (isok) {
                    this.$message.error("输入不规范,请重新输入")
                    this.goodsInfo.secproportion = ""
                } else {
                    if (price < 0 || price > 100) {
                        this.$message.error("商品佣金不能大于100%或小于0%")
                        this.goodsInfo.secproportion = ""
                    }
                }
            },

            //  点击相册加入主图
            getImage(item) {
                let inx = this.goodsInfo.mainImage.indexOf(item)
                let length = this.goodsInfo.mainImage.length
                if (inx == -1) {
                    if (length < 5 ) {
                        this.goodsInfo.mainImage.push(item)
                        this.mainLimit = 5 - length - 1
                    } else {
                        this.$message.error("主图最多5张")
                        this.MainisReady = false
                        this.mainLimit = 0
                        return false
                    }
                } else {
                    this.$message.error("已添加过该图片")
                    return false
                }
            },

            // 点击单张主图 删除
            deleteImg( tag ) {
                this.goodsInfo.mainImage.splice(this.goodsInfo.mainImage.indexOf(tag), 1);
                let length = this.goodsInfo.mainImage.length 
                if (length < 5) {
                    this.mainLimit = 5 - length 
                    this.MainisReady = true
                }
            },
            
            // 点击删除详情页
            // deleteImgList( index ) {
            //     this.goodsInfo.ImageList.splice(index, 1);
            //     let length = this.goodsInfo.ImageList.length 
            //     if (length < 15) {
            //         this.mainLimit = 15 - length 
            //         this.ListisReady = true
            //     } else {
            //         this.ListisReady = false 
            //         this.ListLimit = 0
            //     }
            // },

            // 添加规格

            addGuide() {
                console.log(1);
                
                this.goodsInfo.guide.push({
                    name: "",
                    price: "",
                    stock: ""
                })
                console.log(this.goodsInfo.guide);
                
            },

            // 删除guide


            DeleteGuide( index ) {
                this.goodsInfo.guide.splice(index, 1)
            },

            //  点击相册加入详情页
            // getImageLists(item) {
            //     let length = this.goodsInfo.ImageList.length
            //     let isok = this.goodsInfo.ImageList.indexOf( item )
            //     if (isok == -1) {
            //         if (length < 15 ) {
            //             this.goodsInfo.ImageList.push(item)
            //             this.ListLimit = 15 - length - 1
            //         } else {
            //             this.$message.error("详情页最多15张")
            //             this.ListisReady = false
            //             this.ListLimit = 0
            //             return false
            //         }
            //     } else {
            //         this.$message.error("已添加过该图片")
            //         return false
            //     }
            // },

            // 点击取消

            Cancel() {
                this.$router.go(-1)
            },

            // 检测添加的规格是否规范

            checkGuide() {
                let bl = false
                let arr = this.goodsInfo.guide 
                console.log(arr);
                
                arr.forEach(el => {
                    if (el.price && el.name && el.stock) {
                        bl = true
                    } else {
                        bl = false
                    }
                })

                return bl
            },

            //  点击确定添加商品

            async addGoodsInfo() {

                console.log(this.goodsInfo);
                
                let { title , price, stock } = this.goodsInfo
                let checked = this.checkGuide()
                console.log(checked);
                
                if (!title) {
                    this.$message.error("请输入产品标题")
                    return false
                } else if (!price) {
                    this.$message.error("请输入产品价格")
                    return false
                } else if (!stock) {
                    this.$message.error("请输入产品库存")
                    return false
                } else if (!checked) {
                    this.$message.error("商品规格不规范")
                    return false
                } else {
                    let res = await this.$axios.post("/admin/addGoods", this.goodsInfo)
                    let code = res.data.code
                    if (code == 202 || code == 204) {
                        this.$message.success("更新成功")
                        this.goodsInfo = {}
                        this.$router.push("/goodsList")
                    } else {
                        this.$message.error("更新失败,请重试")
                        return false
                    }
                }
            },
            
        },
    }
</script>

<style lang="scss" scoped>
 #addGoods {
     width: 100%;
     box-sizing: border-box;
     .title {
         width: 100%;
         display: flex;
         align-items: center;
         border-bottom: 1px solid #f5f5f5;
         .btn {
             width: 300px;
         }
     }
     .btnbox {
         width: 850px;
         text-align: center;
         .el-button {
             margin: 10px 20px;
         }
     }
     .el-input {
         max-width: 850px;
     }
     .el-tabs {
         max-width: 850px;;
     }
     .mainimglist {
         width: 850px;
         display: flex;
         img {
             width: 148px;
             height: 148px;
             margin: 0 5px;
         }
     }
     .allimglist {
         max-width: 800px;
         display: flex;
         flex-wrap: wrap;
         img {
             width: 148px;
             height: 148px;
             margin: 5px;
         }
     }
     .classbox {
         width: 100%;
         display: flex;
         .addClass {
            .el-tag {
                margin: 0 10px;
            }
         }
     }
     .guides {
         width: 850px;
         .guidebox {
             width: 100%;
             display: flex;
             margin: 5px 0;
             padding: 5px 0;
             border-bottom: 1px solid #f2f2f2;
             border-radius: 20px;
             .name {
                 width: 80px;
                 text-align: center;
             }
             .guide_name {
                 display: flex;
             }
             .guide_price {
                 display: flex;
             }
             .guide_stock {
                 display: flex;
             }
             .close {
                 width: 30px;
                 text-align: center;
                 cursor: pointer;
             }
         }
     }
     .imglist {
         width: 850px;
         padding: 0 50px;
         img {
             width: 750px;
             display: flex;
         }
     }
 }
</style>